/* Copyright (c) 2024 Huawei Technologies Co., Ltd.
openFuyao is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN 'AS IS' BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details. */
import BreadCrumbCom from '@/components/BreadCrumbCom';
import { containerRouterPrefix, ResponseCode, DEFAULT_CURRENT_PAGE, BusinessCode } from '@/common/constants';
import '@/styles/pages/dashboard.less'
import { Fragment, useCallback, useEffect, useState } from 'openinula';
import { requestResource, sortData, filterData } from '@/tools/utils';
import { getMonitorDashboardList, deleteDashboard, createEachDashboard, updateEachDashboard } from '@/api/monitorApi';
import { Radio, Button, Pagination, ConfigProvider, Popover, Table, message, Tooltip } from 'antd';
import { UnorderedListOutlined, AppstoreOutlined, MoreOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import zhCN from 'antd/es/locale/zh_CN';
import EmptyHandle from '@/components/EmptyHandle';
import emptyDashboardImg from '@/assets/images/chart/emptyDashboard.png';
import CreateMonitorBoardModal from '@/components/CreateMonitorBoardModal';
import DeleteInfoModal from '@/components/DeleteInfoModal';
import { useHistory, Link } from 'inula-router';

export default function DashBoard() {
  const history = useHistory();
  const [dashBoardList, setDashBoardList] = useState([]);
  const [showDashBoardList, setShowDashBoardList] = useState([]);
  const [showListValue, setShowListValue] = useState('Card');
  const [dashBoardPage, setDashBoardPage] = useState(DEFAULT_CURRENT_PAGE);
  const [dashBoardPageSize, setDashBoardPageSize] = useState(20);
  const [loading, setLoading] = useState(true);
  const [monitorBoardModalOpen, setMonitorBoardModalOpen] = useState(false);
  const [modalType, setModalType] = useState('create');
  const [modalBoardName, setModalBoardName] = useState('');
  const [openUid, setOpenUid] = useState('');
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [isMonitorDelCheck, setIsMonitorDelCheck] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();
  const [handleDashboardID, setHandleDashboardID] = useState('');
  const [sortObj, setSortObj] = useState({}); // 排序
  const [originalData, setOriginalData] = useState([]); // 原始数据
  const [creatorFilter, setCreatorFilter] = useState([]);
  const [filterValue, setFilterValue] = useState(''); // 创建者筛选项

  const options = [
    { label: <div><AppstoreOutlined style={{ color: showListValue === 'Card' ? '#fff' : '#333333' }} /></div>, value: 'Card' },
    { label: <div><UnorderedListOutlined style={{ color: showListValue === 'List' ? '#fff' : '#333333' }} /></div>, value: 'List' },
  ];

  const handleChangeShowStyle = ({ target: { value } }) => {
    setShowListValue(value);
  };

  const getDashBoardData = useCallback(async () => {
    setLoading(true);
    const [error, res] = await requestResource(getMonitorDashboardList());
    if (error) {
      messageApi.error('获取数据看板失败');
      setDashBoardList([]); // 异常
      setOriginalData([]);
      setLoading(false);
    }
    if (res) {
      if (res.data.code === ResponseCode.OK) {
        // 设置创建者列表
        let creatorList = [];
        let finallyList = [];
        if (res.data.data) {
          setDashBoardList([...res.data.data]);
          setOriginalData([...res.data.data]);
          res.data.data.map(item => {
            creatorList.push(item.creator);
          });
          [...new Set(creatorList)].map(item => {
            finallyList.push({ text: item, value: item });
          });
        } else {
          setDashBoardList([]);
          setOriginalData([]);
        }
        setCreatorFilter(finallyList);
        setLoading(false);
      }
    }
  }, []);

  const handleDashboardPageChange = (current, limit) => {
    setDashBoardPage(current);
    setDashBoardPageSize(limit);
  };

  const handleAddUUid = (record) => {
    setOpenUid(record.dashboardID);
    setHandleDashboardID(record.dashboardID);
  };

  const handleMonitorDashboardModify = (name) => {
    setOpenUid('');
    setModalBoardName(name);
    setModalType('edit');
    setMonitorBoardModalOpen(true);
  };

  const dashBoardColumns = [
    {
      title: '名称',
      key: 'name',
      sorter: true,
      sortOrder: sortObj.columnKey === 'name' ? sortObj.order : null,
      render: (_, record) => <Link to={{ pathname: `/dashboard/bigDataDashboard/detail/${record.dashboardID}/${encodeURIComponent(record.displayName)}` }}>{record.displayName}</Link>,
    },
    {
      title: '监控组件数',
      key: 'monitorComponentNum',
      sorter: true,
      sortOrder: sortObj.columnKey === 'monitorComponentNum' ? sortObj.order : null,
      render: (_, record) => record.totalWidgets,
    },
    {
      title: '创建者',
      key: 'creator',
      filters: creatorFilter,
      filterMultiple: false,
      sorter: true,
      sortOrder: sortObj.columnKey === 'creator' ? sortObj.order : null,
      render: (_, record) => record.creator,
    },
    {
      title: '更新时间',
      key: 'lastUpdateTime',
      sorter: true,
      sortOrder: sortObj.columnKey === 'lastUpdateTime' ? sortObj.order : null,
      render: (_, record) => dayjs(record.lastUpdateTime).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'handle',
      render: (_, record) => <Popover
        placement="bottom"
        getPopupContainer={(triggerNode) => {
          if (triggerNode && triggerNode.parentNode) {
            return triggerNode.parentNode;
          }
          return document.body;
        }}
        content={<div className='pop_modal'>
          <Button type='link' className='monitor_link_btn' onClick={() => handleMonitorDashboardModify(record.displayName)}>修改</Button>
          <Button type='link' className='monitor_link_btn' onClick={() => handleMonitorDashboardDel(record.displayName)}>删除</Button>
        </div>}
        trigger="click"
        arrow={false}
        open={openUid === record.dashboardID}
        onOpenChange={(newOpen) => newOpen ? handleAddUUid(record) : setOpenUid('')}
      >
        <MoreOutlined style={{ color: '#356AC4' }} />
      </Popover>
    }
  ];

  const handleCreateMonitorBoard = () => {
    setOpenUid('');
    setModalType('create');
    setModalBoardName('');
    setMonitorBoardModalOpen(true);
  };

  const handleCancelMonitorBoard = () => {
    setMonitorBoardModalOpen(false);
  };

  const handleConfirmMonitorBoard = async (name) => {
    if (modalType === 'create') {
      const localUser = localStorage.getItem('user');
      const jsonData = {
        displayName: name,
        creator: localUser ? JSON.parse(localUser).name : 'admin',
      };
      const [error, res] = await requestResource(createEachDashboard(jsonData));
      if (error) {
        if (error.response.status === ResponseCode.Forbidden) {
          messageApi.error('操作失败，当前用户没有操作权限，请联系管理员添加权限！');
        } else {
          if (error.response.data.code === BusinessCode.DuplicateName) {
            messageApi.error('该名称已存在！');
          } else {
            messageApi.error('创建失败！');
          }
        }
      }
      if (res) {
        if (res.data.code === ResponseCode.OK) {
          messageApi.success('创建成功！');
          setMonitorBoardModalOpen(false);
          getDashBoardData();
        }
      }
    } else {
      const data = {
        displayName: name,
      }
      const [error, res] = await requestResource(updateEachDashboard(handleDashboardID, data));
      if (error) {
        if (error.response.status === ResponseCode.Forbidden) {
          messageApi.error('操作失败，当前用户没有操作权限，请联系管理员添加权限！');
        } else {
          if (error.response.data.code === BusinessCode.DuplicateName) {
            messageApi.error('该名称已存在！');
          } else {
            messageApi.error('修改失败！');
          }
        }
      }
      if (res) {
        if (res.data.code === ResponseCode.OK) {
          messageApi.success('修改成功！');
          setMonitorBoardModalOpen(false);
          getDashBoardData();
        }
      }
    }
  };

  const handleMonitorDashboardDel = (name) => {
    setModalBoardName(name);
    setOpenUid('');
    setDeleteModalOpen(true);
  };

  useEffect(() => {
    if (showListValue === 'Card') {
      setDashBoardPageSize(20);
      setDashBoardPage(DEFAULT_CURRENT_PAGE);
    } else {
      setDashBoardPageSize(10);
      setDashBoardPage(DEFAULT_CURRENT_PAGE);
    }
  }, [showListValue]);

  useEffect(() => {
    let list = [];
    list = dashBoardList.slice((dashBoardPage - 1) * dashBoardPageSize, (dashBoardPage - 1) * dashBoardPageSize + dashBoardPageSize);
    setShowDashBoardList([...list]);
  }, [dashBoardPage, dashBoardPageSize, JSON.stringify(dashBoardList)]);

  useEffect(() => {
    let newList = originalData;
    if (sortObj) {
      newList = sortData(originalData, sortObj);
    }
    if (filterValue) {
      newList = filterData(newList, filterValue);
    }
    setDashBoardList([...newList]);
  }, [sortObj, JSON.stringify(originalData), filterValue]);

  const handleDelModalCancel = () => {
    setDeleteModalOpen(false);
    setIsMonitorDelCheck(false);
  };

  const handleMonitorCheckFn = (e) => {
    setIsMonitorDelCheck(e.target.checked);
  };

  const handleDelMonitorConfirm = async (uuid) => {
    const [error, res] = await requestResource(deleteDashboard(uuid));
    if (error) {
      if (error.response.status === ResponseCode.Forbidden) {
        messageApi.error('操作失败，当前用户没有操作权限，请联系管理员添加权限！');
      } else {
        messageApi.error('删除失败！');
      }
    }
    if (res) {
      if (res.data.code === ResponseCode.OK) {
        messageApi.success('删除成功！');
        setIsMonitorDelCheck(false);
        setDeleteModalOpen(false);
        getDashBoardData();
      }
    }
  };

  const handleTableChange = (_pagination, filters, sorter, extra) => {
    if (extra.action === 'sort') {
      setSortObj({ columnKey: sorter.columnKey, order: sorter.order });
      setDashBoardPage(1);
    }
    if (extra.action === 'filter') {
      setFilterValue(filters.creator ? filters.creator[0] : '');
      setDashBoardPage(1);
    }
  };

  const handleSkip = (uuid, name) => {
    history.push({ pathname: `/dashboard/bigDataDashboard/detail/${uuid}/${encodeURIComponent(name)}` });
  };

  useEffect(() => {
    getDashBoardData();
  }, [getDashBoardData]);

  return <div className="child_content">
    {contextHolder}
    <BreadCrumbCom className="create_bread" items={[
      { title: '自定义监控看板', path: `/${containerRouterPrefix}/dashboard` },
    ]} />
    <div className='dashboard_box'>
      <div className='dashboard_header'>
        <h2>监控看板<span>({dashBoardList.length})</span></h2>
        <div className='dashboard_tools'>
          <Radio.Group
            className='toogle_btn'
            options={options}
            onChange={handleChangeShowStyle}
            value={showListValue}
            optionType="button"
            buttonStyle="solid"
          />
          <Button className='monitor_primary_btn' onClick={handleCreateMonitorBoard}>创建监控看板</Button>
        </div>
      </div>
      {!loading ? <div className='dashboard_content'>
        {showDashBoardList.length ?
          <Fragment>
            {showListValue === 'Card' && <Fragment>
              <div className='dashboard_card'>
                {showDashBoardList.map(item =>
                  <div className='card_item' onClick={() => handleSkip(item.dashboardID, item.displayName)}>
                    <div className='card_header'>
                      <Tooltip title={item.displayName} placement='topLeft'><h4>{item.displayName}</h4></Tooltip>
                      <Popover
                        placement="bottom"
                        content={<div className='pop_modal'>
                          <Button type='link' className='monitor_link_btn' onClick={e => { e.stopPropagation(); handleMonitorDashboardModify(item.displayName) }}>修改</Button>
                          <Button type='link' className='monitor_link_btn' onClick={e => { e.stopPropagation(); handleMonitorDashboardDel(item.displayName) }}>删除</Button>
                        </div>}
                        trigger="click"
                        getPopupContainer={(triggerNode) => {
                          if (triggerNode && triggerNode.parentNode) {
                            return triggerNode.parentNode;
                          }
                          return document.body;
                        }}
                        arrow={false}
                        open={openUid === item.dashboardID}
                        onOpenChange={(newOpen) => newOpen ? handleAddUUid(item) : setOpenUid('')}
                      >
                        <MoreOutlined style={{ color: '#356AC4' }} onClick={e => e.stopPropagation()} />
                      </Popover>
                    </div>
                    <div className='card_body'>
                      <div className='monitor_component'>
                        <span>监控组件数:<span className='word'>{item.totalWidgets}</span></span>
                      </div>
                      <div className='monitor_description'>
                        <Tooltip title={`${item.creator}创建`}><div className='name'>{`${item.creator}创建`}</div></Tooltip>
                        <div className='time'>{dayjs(item.lastUpdateTime).format('YYYY-MM-DD HH:mm')}更新</div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
              <ConfigProvider locale={zhCN}>
                <Pagination
                  className='page'
                  total={dashBoardList.length}
                  pageSize={dashBoardPageSize}
                  current={dashBoardPage}
                  showTotal={(total) => `共${total}条`}
                  showSizeChanger
                  showQuickJumper
                  pageSizeOptions={[20, 50]}
                  onChange={handleDashboardPageChange}
                />
              </ConfigProvider>
            </Fragment>}
            {showListValue === 'List' && <div className='dashboard_table'>
              <ConfigProvider locale={zhCN}>
                <Table
                  loading={loading}
                  dataSource={showDashBoardList}
                  columns={dashBoardColumns}
                  pagination={false}
                  onChange={handleTableChange}
                />
                <Pagination
                  className='page'
                  total={dashBoardList.length}
                  pageSize={dashBoardPageSize}
                  current={dashBoardPage}
                  showTotal={(total) => `共${total}条`}
                  showSizeChanger
                  showQuickJumper
                  pageSizeOptions={[10, 20, 50]}
                  onChange={handleDashboardPageChange}
                />
              </ConfigProvider>
            </div>}
          </Fragment>
          : <EmptyHandle imgSrc={emptyDashboardImg} description='暂无监控看板'> <Button onClick={handleCreateMonitorBoard}>创建监控看板</Button></EmptyHandle>}
      </div> : <div className='dashboard_content' />}
      <CreateMonitorBoardModal
        title={modalType === 'create' ? '创建监控看板' : '修改监控看板'}
        open={monitorBoardModalOpen}
        name={modalBoardName}
        cancelFn={handleCancelMonitorBoard}
        okFn={handleConfirmMonitorBoard}
      />
    </div>
    <DeleteInfoModal
      title='删除监控看板'
      open={deleteModalOpen}
      cancelFn={handleDelModalCancel}
      content={[
        '删除监控看板后将无法恢复，请谨慎操作。',
        `确定删除 ${modalBoardName} 吗？`,
      ]}
      isCheck={isMonitorDelCheck}
      showCheck={true}
      checkFn={handleMonitorCheckFn}
      confirmFn={() => handleDelMonitorConfirm(handleDashboardID)} />
  </div>
}